<?php

//$mcrp = './../';
include_once($mcrp . 'functions/session.php');
include_once($mcrp . 'functions/contests.php');
include_once($mcrp . 'functions/users.php');
include_once($mcrp . 'functions/log.php');

if(!defined('VALID_TIMEOUT')) define('VALID_TIMEOUT', 4);

function ValidateContest($Success, $contest)
{
	global $mcuser;
	if($mcuser->id == 0) { Disconnect(); return 0; }
	$ci = GetContestById($contest);	
	
	if($mcuser->isadmin == 1 && isset($_SESSION['test']))
	{
		if($Success == true)
			echo 'Validated:<span style="color:green;">OK</span><br />';
		else
			echo 'Validated:<span style="color:red;">FAILED</span><br />';
		echo '<pre>';
		print_r($_SESSION['var']);
		print_r($_POST);
		echo '</pre>';
		exit;
	}
	
	$time = time() - $_SESSION['mctime'];
	$Timeout = ($time > VALID_TIMEOUT);
	LogTry($ci, $Success, $Timeout, $time);
	if($Success == false || $Timeout == true) { Disconnect(); return 0; }
	
	// if($ci->visible == 0 && $mcuser->isadmin == 0) return 0;
	if(in_array($contest, $mcuser->contestcompleted) == true) { Disconnect(); return 0; }
	$mcuser->points += $ci->points;
	$mcuser->contestcompleted[] = $contest;
	$OldRank = $mcuser->rank;
	$mcuser->rank = ComputeSingleRank($mcuser->points);
	if($OldRank != $mcuser->rank)
	{
		$users = GetAllUsersByPoints($mcuser->rank - 1, $OldRank - $mcuser->rank);
		foreach($users as $u)
		{
			$u->rank++;
			UpdateUser($u);
		}
	}
	UpdateUser($mcuser);
	
	$ci->validationcount++;
	$OldPoints = $ci->points;
	if(ComputeContestPoints($ci))
		UpdateUsersPoints($contest, $OldPoints - $ci->points);
	UpdateContest($ci);
	AddLastValidation($mcuser->id, $ci->id);
	Disconnect();
	return $ci->points;
}

function CheckUser()
{
	global $mcuser;
	if($mcuser->id == 0) return 0;
}

function Disconnect()
{
	unset($_SESSION['mcuser']);
	session_destroy();
	$mcuser = null;
}

?>